<template>
  <div class="search">
    <van-nav-bar
      title="搜索中心"
      left-arrow
      @click-left="$router.back()"
    ></van-nav-bar>

    <!-- 搜索框 -->
    <van-search
      v-model.trim="value"
      show-action
      shape="round"
      placeholder="请输入搜索关键词"
      @search="onSearch(value)"
      @input="inputFn"
    >
      <template #action>
        <div @click="onSearch(value)">搜索</div>
      </template>
    </van-search>

    <!-- 建议列表 -->
    <van-cell-group v-if="value">
      <!-- :title="highLight(item, value)"
        不识别span标签, 导致导量没有效果-->
      <van-cell
        v-for="item in optionsList"
        icon="search"
        :key="item"
        @click="onSearch(item)"
      >
        <!-- 关键字高亮处理 -->
        <span v-html="highLight(item, value)">哈哈哈</span>
      </van-cell>
    </van-cell-group>

    <!-- 历史记录 -->
    <van-cell-group v-else>
      <van-cell title="历史记录"></van-cell>
      <van-cell
        v-for="item in historySearch"
        :key="item"
        :title="item"
        @click="onSearch(item)"
      >
        <van-icon name="close" @click="delHistory(item)" />
      </van-cell>
    </van-cell-group>
  </div>
</template>

<script>
import { getSuggest } from '@/api/search'
import { setStorageHistory, getStorageHistory } from '@/utils/storage'

export default {
  name: 'Search',
  data() {
    return {
      value: '',
      optionsList: [],
      historySearch: getStorageHistory()
    }
  },
  methods: {
    highLight(str, keyword) {
      return str.replace(new RegExp(keyword, 'gi'), item => {
        return `<span style="color: red">${keyword}</span>`
      })
    },
    onSearch(keyword) {
      // 先把搜索的关键字存储起来
      // 要求: 最新的在最前面 + 不能重复

      // 先过滤  再加到最前面
      this.historySearch = this.historySearch.filter(item => item !== keyword)
      this.historySearch.unshift(keyword)

      // 将数组本地存储起来
      setStorageHistory(this.historySearch)

      // 跳转搜索结果页面
      console.log(keyword)

      this.$router.push({
        path: '/search/result',
        // 还要带伤关键字
        query: {
          keyword
        }
      })
    },
    inputFn(value) {
      // 优化  防抖
      clearTimeout(this.timerId)

      // 把延时器的id返回出来, 赋值给this的timerId 属性
      this.timerId = setTimeout(async () => {
        if (!this.value) {
          // 如果没有内容就不搜索,不发送请求
          // 并且清空数组optionsList
          this.optionsList = []
          return
        }
        try {
          const res = await getSuggest(this.value)
          console.log(res)
          this.optionsList = res.data.options
        } catch (e) {}
      }, 300)
    },

    delHistory(value) {
      this.historySearch = this.historySearch.filter(item => item !== value)

      // 删除之后重新存储
      setStorageHistory(this.historySearch)
    }
  }
}
</script>

<style lang="less" scoped></style>
